using System;
using System.Collections.Generic;
using System.Drawing;
using System.Windows.Forms;

namespace MouseKeyboardOperationSimulator
{
    /// <summary>
    /// DataGridView操作管理类
    /// </summary>
    public class DataGridViewManager
    {
        private DataGridView _dataGridView;
        private Dictionary<string, string[]> _operationTypes;
        private Dictionary<string, string> _operationExamples;
        private int _lastFocusedRow = -1;
        private int _lastFocusedColumn = -1;
        private ToolTip _toolTip; // 添加ToolTip组件
        private ThemeManager _themeManager; // 主题管理器

        /// <summary>
        /// 构造函数
        /// </summary>
        public DataGridViewManager(DataGridView dataGridView, ThemeManager themeManager = null)
        {
            _dataGridView = dataGridView;
            _toolTip = new ToolTip(); // 初始化ToolTip组件
            _themeManager = themeManager;
            InitializeOperationTypes();
            InitializeOperationExamples();
            SubscribeEvents();
        }

        /// <summary>
        /// 初始化操作类型字典
        /// </summary>
        private void InitializeOperationTypes()
        {
            _operationTypes = new Dictionary<string, string[]>
            {
                { "鼠标", new string[] { "移动到坐标", "左键单击", "左键双击", "右键单击", "右键双击", "中键单击", "鼠标滚轮", "左键拖动" } },
                { "键盘", new string[] { "单击按键", "按下按键", "释放按键"} },
                { "延时", new string[] { "时长" } },
                { "循环", new string[] { "开始", "结束" } },
            };
        }

        /// <summary>
        /// 初始化操作示例字典
        /// </summary>
        private void InitializeOperationExamples()
        {
            _operationExamples = new Dictionary<string, string>
            {
                { "移动到坐标", "示例: 100,200" },
                { "左键单击", "示例: 100,200" },
                { "左键双击", "示例: 100,200" },
                { "右键单击", "示例: 100,200" },
                { "右键双击", "示例: 100,200" },
                { "中键单击", "示例: 100,200" },
                { "鼠标滚轮", "示例: 1 (正数向上滚动，负数向下滚动，单位：1表示向上滚动一下)" },
                { "左键拖动", "示例: 100,200;500;300,400 (起始坐标;拖动时长毫秒数;结束坐标)" },
                { "单击按键", "示例: A, F1, Enter, Ctrl+A" },
                { "按下按键", "示例: Ctrl, Shift, Alt, Ctrl+A" },
                { "释放按键", "示例: Ctrl, Shift, Alt, Ctrl+A" },
                { "时长", "示例: 1000 (单位: 毫秒)" },
                { "开始", "示例: 5 (循环5次) 或留空 (无限循环)" },
                { "结束", "留空" },
            };
        }

        /// <summary>
        /// 订阅事件
        /// </summary>
        private void SubscribeEvents()
        {
            _dataGridView.CellValueChanged += DataGridView_CellValueChanged;
            _dataGridView.CurrentCellDirtyStateChanged += DataGridView_CurrentCellDirtyStateChanged;
            _dataGridView.DataError += DataGridView_DataError;
            _dataGridView.EditingControlShowing += DataGridView_EditingControlShowing;
            _dataGridView.CellClick += DataGridView_CellClick;
            _dataGridView.UserAddedRow += DataGridView_UserAddedRow;
            _dataGridView.UserDeletedRow += DataGridView_UserDeletedRow;
            _dataGridView.CellMouseEnter += DataGridView_CellMouseEnter;
            _dataGridView.CellMouseLeave += DataGridView_CellMouseLeave;
            _dataGridView.SelectionChanged += DataGridView_SelectionChanged;
        }

        public DataGridViewCell GetCell(int rowIndex, string columnName)
        {
            if (rowIndex >= 0 && rowIndex < _dataGridView.Rows.Count)
            {
                return _dataGridView.Rows[rowIndex].Cells[columnName];
            }
            return null;
        }

        /// <summary>
        /// 获取当前选中的单元格行和列
        /// </summary>
        /// <summary>
        /// 获取指定单元格的值
        /// </summary>
        public object GetCellValue(int rowIndex, string columnName)
        {
            return GetCell(rowIndex, columnName)?.Value;
        }

        /// <summary>
        /// 获取当前行的操作类型
        /// </summary>
        public string GetCurrentOperationType(int rowIndex)
        {
            if (rowIndex >= 0 && rowIndex < _dataGridView.Rows.Count)
            {
                return GetCellValue(rowIndex, "OperationType")?.ToString();
            }
            return null;
        }

        /// <summary>
        /// 获取列索引
        /// </summary>
        public int GetColumnIndex(string columnName)
        {
            return _dataGridView.Columns[columnName].Index;
        }

        /// <summary>
        /// 更新操作类型选项
        /// </summary>
        public void UpdateOperationTypeOptions(int rowIndex, string deviceType)
        {
            try
            {
                // 边界检查
                if (rowIndex < 0 || rowIndex >= _dataGridView.Rows.Count)
                    return;

                // 获取操作类型单元格
                var cell = GetCell(rowIndex, "OperationType");
                var operationTypeCell = cell as DataGridViewComboBoxCell;
                if (operationTypeCell == null)
                    return;

                // 清空现有选项
                operationTypeCell.Items.Clear();

                // 根据设备类型添加相应的操作类型选项
                if (!string.IsNullOrEmpty(deviceType) && _operationTypes.ContainsKey(deviceType))
                {
                    foreach (string operation in _operationTypes[deviceType])
                    {
                        operationTypeCell.Items.Add(operation);
                    }

                    // 如果有选项，则设置为第一个选项作为默认值
                    if (operationTypeCell.Items.Count > 0)
                    {
                        operationTypeCell.Value = operationTypeCell.Items[0];
                    }
                    else
                    {
                        operationTypeCell.Value = null;
                    }
                }
                else
                {
                    // 如果设备类型为空或不在字典中，清空值
                    operationTypeCell.Value = null;
                }
            }
            catch (Exception ex)
            {
                // 记录异常但不抛出，防止程序崩溃
                System.Diagnostics.Debug.WriteLine($"UpdateOperationTypeOptions error: {ex.Message}");
            }
        }

        /// <summary>
        /// 更新所有行的序号
        /// </summary>
        public void UpdateRowNumbers()
        {
            // 更新所有行的序号
            for (int i = 0; i < _dataGridView.Rows.Count; i++)
            {
                // 为所有行设置序号，包括新行
                var cell = GetCell(i, "Index") as DataGridViewTextBoxCell;
                if (cell != null)
                {
                    cell.Value = (i + 1).ToString();
                }
            }
        }

        #region Event Handlers

        public void DataGridView_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)
        {
            DataGridView dgv = sender as DataGridView;
            
            // 解决ComboBox需要点击两次才能展开的问题
            if (e.Control is ComboBox comboBox)
            {
                // 确保ComboBox样式为下拉列表
                comboBox.DropDownStyle = ComboBoxStyle.DropDownList;
                
                // 让ComboBox获得焦点
                comboBox.Focus();
                
                // 移除之前的事件处理程序（如果有的话）
                comboBox.SelectedIndexChanged -= ComboBox_SelectedIndexChanged;
                // 添加事件处理程序来优化用户体验
                comboBox.SelectedIndexChanged += ComboBox_SelectedIndexChanged;
            }
            // 为操作内容列添加输入验证
            else if (dgv.CurrentCell.ColumnIndex == GetColumnIndex("OperationContent") && e.Control is TextBox textBox)
            {
                // 移除之前的事件处理程序（如果有的话）
                textBox.TextChanged -= OperationContentTextBox_TextChanged;
                textBox.Leave -= OperationContentTextBox_Leave;
                
                // 添加事件处理程序来验证输入
                textBox.TextChanged += OperationContentTextBox_TextChanged;
                textBox.Leave += OperationContentTextBox_Leave;
                textBox.Enter += OperationContentTextBox_Enter;
            }
        }
        
        private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            // 当用户选择了新的索引后，可以在这里添加额外的处理逻辑
            if (sender is ComboBox comboBox)
            {
                // 如果需要在选择改变时做些什么，可以在这里处理
            }
        }

        public void DataGridView_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            // 检查是否点击的是有效行
            if (e.RowIndex >= 0)
            {
                // 检查是否点击的是ComboBox列
                if (e.ColumnIndex == GetColumnIndex("DeviceType") || e.ColumnIndex == GetColumnIndex("OperationType"))
                {
                    // 开始编辑模式
                    _dataGridView.BeginEdit(true);
                    
                    // 获取编辑控件
                    ComboBox comboBox = _dataGridView.EditingControl as ComboBox;
                    if (comboBox != null)
                    {
                        // 显示下拉列表
                        comboBox.DroppedDown = true;
                    }
                }
                // 检查是否点击的是操作内容列
                else if (e.ColumnIndex == GetColumnIndex("OperationContent"))
                {
                    // 开始编辑模式
                    _dataGridView.BeginEdit(true);
                }
            }
        }

        public void DataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)
        {
            // 当设备类型列发生变化时，更新操作类型列的选项
            if (e.ColumnIndex == GetColumnIndex("DeviceType") && e.RowIndex >= 0)
            {
                string deviceType = GetCellValue(e.RowIndex, "DeviceType")?.ToString();
                
                // 获取当前操作内容
                string operationContent = GetCellValue(e.RowIndex, "OperationContent")?.ToString();
                
                // 获取原来的操作类型
                string oldOperationType = GetCellValue(e.RowIndex, "OperationType")?.ToString();
                
                // 更新操作类型选项
                UpdateOperationTypeOptions(e.RowIndex, deviceType);
                
                // 如果操作内容不为空，验证其合法性
                if (!string.IsNullOrEmpty(operationContent))
                {
                    // 获取新的操作类型
                    string newOperationType = GetCurrentOperationType(e.RowIndex);
                    
                    // 验证操作内容的合法性
                    ValidateAndHandleOperationContent(e.RowIndex, newOperationType, operationContent);
                }
            }
            // 当操作类型列发生变化时
            else if (e.ColumnIndex == GetColumnIndex("OperationType") && e.RowIndex >= 0)
            {
                string operationType = GetCellValue(e.RowIndex, "OperationType")?.ToString();
                
                // 获取当前操作内容
                string operationContent = GetCellValue(e.RowIndex, "OperationContent")?.ToString();
                
                // 如果操作内容不为空，验证其合法性
                if (!string.IsNullOrEmpty(operationContent))
                {
                    // 验证操作内容的合法性
                    ValidateAndHandleOperationContent(e.RowIndex, operationType, operationContent);
                }
            }
        }

        public void DataGridView_CurrentCellDirtyStateChanged(object sender, EventArgs e)
        {
            // 立即提交编辑更改，以便CellValueChanged事件能够及时触发
            if (_dataGridView.IsCurrentCellDirty)
            {
                _dataGridView.CommitEdit(DataGridViewDataErrorContexts.Commit);
            }
        }

        public void DataGridView_DataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            // 处理DataGridView中的数据错误，防止程序崩溃
            // 特别是处理DataGridViewComboBoxCell值无效的情况
            if (e.Exception is ArgumentException && (e.Context == DataGridViewDataErrorContexts.Formatting || 
                                                   e.Context == DataGridViewDataErrorContexts.Commit))
            {
                // 当发生ComboBox值无效的错误时，清除单元格的值
                DataGridView dgv = sender as DataGridView;
                if (dgv != null && e.RowIndex >= 0 && e.ColumnIndex >= 0)
                {
                    DataGridViewCell cell = dgv.Rows[e.RowIndex].Cells[dgv.Columns[e.ColumnIndex].Name];
                    if (cell != null)
                    {
                        cell.Value = null;
                    }
                }
                
                // 标记错误已处理
                e.ThrowException = false;
            }
            else if (e.Context == DataGridViewDataErrorContexts.Parsing)
            {
                // 处理解析错误
                DataGridView dgv = sender as DataGridView;
                if (dgv != null && e.RowIndex >= 0 && e.ColumnIndex >= 0)
                {
                    DataGridViewCell cell = dgv.Rows[e.RowIndex].Cells[dgv.Columns[e.ColumnIndex].Name];
                    if (cell != null)
                    {
                        cell.Value = null;
                    }
                }
                
                // 标记错误已处理
                e.ThrowException = false;
            }
        }

        public void DataGridView_UserAddedRow(object sender, DataGridViewRowEventArgs e)
        {
            // 当用户添加新行时，更新所有行的序号
            UpdateRowNumbers();
            
            // 设置新行选择列的复选框默认为选中状态
            int checkStatusColumnIndex = GetColumnIndex("CheckStatus");
            if (checkStatusColumnIndex >= 0 && e.Row.Cells[checkStatusColumnIndex] != null)
            {
                e.Row.Cells[checkStatusColumnIndex].Value = true;
            }
        }

        public void DataGridView_UserDeletedRow(object sender, DataGridViewRowEventArgs e)
        {
            // 当用户删除行时，更新所有行的序号
            UpdateRowNumbers();
        }

        public void DataGridView_CellMouseEnter(object sender, DataGridViewCellEventArgs e)
        {
            // 检查是否是操作内容列
            if (e.ColumnIndex == GetColumnIndex("OperationContent") && e.RowIndex >= 0)
            {
                // 获取当前行的操作类型
                string operationType = GetCurrentOperationType(e.RowIndex);

                // 如果操作类型存在且在示例字典中，则显示提示
                if (!string.IsNullOrEmpty(operationType) && _operationExamples.ContainsKey(operationType))
                {
                    string example = _operationExamples[operationType];
                    DataGridViewCell cell = GetCell(e.RowIndex, "OperationContent");
                    if (cell != null)
                    {
                        cell.ToolTipText = example;
                    }
                }
            }
        }

        public void DataGridView_CellMouseLeave(object sender, DataGridViewCellEventArgs e)
        {
            // 清除提示文本
            if (e.ColumnIndex == GetColumnIndex("OperationContent") && e.RowIndex >= 0)
            {
                DataGridViewCell cell = GetCell(e.RowIndex, "OperationContent");
                if (cell != null)
                {
                    cell.ToolTipText = "";
                }
            }
        }

        public void DataGridView_SelectionChanged(object sender, EventArgs e)
        {
            // 记录当前选中的单元格位置
            if (_dataGridView.CurrentCell != null)
            {
                _lastFocusedRow = _dataGridView.CurrentCell.RowIndex;
                _lastFocusedColumn = _dataGridView.CurrentCell.ColumnIndex;
            }
        }

        private void OperationContentTextBox_Enter(object sender, EventArgs e)
        {
            // 检查控件是否已被释放
            if (sender is TextBox textBox && !textBox.IsDisposed)
            {
                // 显示气泡提示
                DataGridView dgv = _dataGridView;
                int rowIndex = dgv.CurrentCell?.RowIndex ?? -1;
                int columnIndex = dgv.CurrentCell?.ColumnIndex ?? -1;

                // 确保是操作内容列
                if (columnIndex == GetColumnIndex("OperationContent") && rowIndex >= 0)
                {
                    // 获取当前行的操作类型
                    string operationType = GetCurrentOperationType(rowIndex);

                    // 如果操作类型存在且在示例字典中，则显示提示
                    if (!string.IsNullOrEmpty(operationType) && _operationExamples.ContainsKey(operationType))
                    {
                        string example = _operationExamples[operationType];
                        // 在文本框上方显示提示，偏移量为0,-25像素
                        _toolTip.Show(example, textBox, 0, -25);
                    }
                }
                
                try
                {
                    // 切换到英文输入法
                    InputMethodHelper.SwitchToEnglishInput();
                }
                catch (Exception ex)
                {
                    // 记录异常但不中断程序执行
                    System.Diagnostics.Debug.WriteLine($"切换输入法时发生错误: {ex.Message}");
                }
            }
        }

        private void OperationContentTextBox_TextChanged(object sender, EventArgs e)
        {
            if (sender is TextBox textBox)
            {
                DataGridView dgv = _dataGridView;
                int rowIndex = dgv.CurrentCell?.RowIndex ?? -1;
                int columnIndex = dgv.CurrentCell?.ColumnIndex ?? -1;

                // 确保是操作内容列
                if (columnIndex == GetColumnIndex("OperationContent") && rowIndex >= 0)
                {
                    string operationType = GetCurrentOperationType(rowIndex);
                    string content = textBox.Text;

                    // 验证输入内容
                    bool isValid = InputValidator.ValidateOperationContent(operationType, content);

                    // 根据验证结果改变背景色
                    textBox.BackColor = isValid ? System.Drawing.Color.White : System.Drawing.Color.LightPink;
                }
            }
        }

        private void OperationContentTextBox_Leave(object sender, EventArgs e)
        {
            if (sender is TextBox textBox)
            {
                // 隐藏提示气泡
                _toolTip.Hide(textBox);
                
                DataGridView dgv = _dataGridView;
                int rowIndex = dgv.CurrentCell?.RowIndex ?? -1;
                int columnIndex = dgv.CurrentCell?.ColumnIndex ?? -1;

                // 确保是操作内容列
                if (columnIndex == GetColumnIndex("OperationContent") && rowIndex >= 0)
                {
                    string operationType = GetCurrentOperationType(rowIndex);
                    string content = textBox.Text;

                    // 验证输入内容
                    bool isValid = InputValidator.ValidateOperationContent(operationType, content);

                    // 如果输入不合法，则清空内容
                    if (!isValid)
                    {
                        textBox.Text = "";
                        textBox.BackColor = System.Drawing.Color.White;
                        
                        // 同时清空单元格的值
                        DataGridViewCell cell = GetCell(rowIndex, "OperationContent");
                        if (cell != null)
                        {
                            cell.Value = "";
                        }
                    }
                }
            }
        }

        #endregion

        #region Input Validation



        /// <summary>
        /// 验证并处理操作内容的合法性
        /// 当设备类型或操作类型改变时调用此方法
        /// </summary>
        /// <param name="rowIndex">行索引</param>
        /// <param name="operationType">操作类型</param>
        /// <param name="content">操作内容</param>
        private void ValidateAndHandleOperationContent(int rowIndex, string operationType, string content)
        {
            // 验证操作内容
            bool isValid = InputValidator.ValidateOperationContent(operationType, content);

            // 如果输入不合法，则清空内容
            if (!isValid)
            {
                // 清空单元格的值
                DataGridViewCell cell = GetCell(rowIndex, "OperationContent");
                if (cell != null)
                {
                    cell.Value = "";
                }
                
                // 如果当前正在编辑该单元格，也要清空编辑控件的内容
                if (_dataGridView.IsCurrentCellInEditMode && 
                    _dataGridView.CurrentCell?.RowIndex == rowIndex && 
                    _dataGridView.CurrentCell?.ColumnIndex == GetColumnIndex("OperationContent"))
                {
                    var editingControl = _dataGridView.EditingControl as TextBox;
                    if (editingControl != null)
                    {
                        editingControl.Text = "";
                        editingControl.BackColor = System.Drawing.Color.White;
                    }
                }
            }
        }



        #endregion
    }
}